package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	. "mwwow_service_go/model"
)

func AddMessage(c *gin.Context) {
	var m Message
	err := json.NewDecoder(c.Request.Body).Decode(&m)
	if err != nil {
		log.Fatalln(err)
	}
	id, err := m.AddMsg()
	if err != nil {
		log.Fatalln(err)
		c.JSON(500, gin.H{
			"code":  1,
			"error": err,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":     0,
		"insertId": id,
	})
}

func DelMessage(c *gin.Context) {
	var m Message
	id := c.Param("id")
	isSuccess, err := m.DeleteMsg(id)
	if err != nil || isSuccess != true {
		log.Fatalln(err)
		c.JSON(500, gin.H{
			"code":  1,
			"error": err,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
	})
}

func GetMessage(c *gin.Context) {
	var m Message
	data, err := m.GetMsg()
	if err != nil {
		log.Fatalln(err)
		c.JSON(500, gin.H{
			"code":  1,
			"error": err,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"data": data,
	})
}
